from math import ceil
import os
import sys
from unittest import expectedFailure


BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
sys.path.append(r'arai_3.0_stop/Source/Astar20221013')

from pipe_tee import *
from duct_tee import *
from Source.SSF import Astar
from Source.HJL import PipeClass
from Source.HJL import BlockClass
from Source.LYZ import pipeAdjust, getHeight
from Source.CMF import avoiding_obstacles
from db_CURD import *
from secondary_main import *
from avoiding_obstacles import find_pipeinfo
# from my_plot import plot_pipes_walls,convert_to_new_format,plot_wall




def main(paths, id):
    user_config = paths[0]
    revit_data = paths[1]
    revit_order = paths[2]

    blockBase = BlockClass.BlockBase(revit_data)
    pipeBase = PipeClass.PipeBase(revit_order)

    pipeBase.sizeOrder()
    # 风管的比例6:1限定
    # pipeBase.duct_scale_modify()
    # pipeBase.sizeOrder_byDistance()

    pipeBase_copy = copy.deepcopy(pipeBase)  # 拷贝pipebase，为了三通fitting而设置
    pipeBase_old = copy.deepcopy(pipeBase_copy)   # 为保存原来基础的pipeBase 方便比较

    block_arr = qyhf.blocks_to_arr(blockBase)
    block_arr_copy = copy.deepcopy(block_arr)
    block_arr = qyhf.pipes_to_blocks(block_arr, 10)  # 加安装空间
    # print('block_arr_copy',block_arr_copy)

    ceilling = [0, 0]
    floor, ceilling[0], ceilling[1], flag = getHeight.get_floor_height(revit_data, user_config)
    # ceilling = [-float('inf'),float('inf')]
    print('ceilling floor', ceilling, floor)
    # if flag:
    #     set_Initial_height(pipeBase, ceilling)

    pipeGroups_arr = pipes_getGroup(pipeBase)
    # print('----', pipeGroups_arr)
    # pipeGroups_arr = setHeight(revit_data,user_config,pipeGroups_arr)

    if (pipeGroups_arr == []):
        print('管道为空')
        errmes = "算法检测到管道为空，请检测输入是否有问题！"
        # setStatus(id, 2)
        return

    new_allpipelist = []
    Group_index = 1
    err_pipegroups = 0
    err_index = {}
    flag = 0  # 算法flag，0为逻辑，1为A*
    for PipeGroup in pipeBase._pipeGroups:
        PipeGroup_info = [PipeGroup.pipeGroupNo, PipeGroup.type, ceilling,
                          floor]  # PipeGroup_info信息为管道组号、管道组类型、天花板高度、地板高度
        try:
            # 如果是不含三通水管,则跑原来程序:
            if PipeGroup._teeList == []:
                print("程序正在运行第" + str(Group_index) + "组管道，一共有" + str(
                    len(pipeGroups_arr)) + "组管道,当前组管道标号pipeGroup = " + str(PipeGroup.pipeGroupNo))

                progress(Group_index - 1, len(pipeGroups_arr))
                message_info("程序正在运行第" + str(Group_index) + "组管道，一共有" + str(len(pipeGroups_arr)) + "组管道")

                print('*************当前组(pipeGroupNo =' + str(PipeGroup.pipeGroupNo) + ')管道不含三通,跑原来算法*************')
                pipegroup_main(pipeBase, blockBase, block_arr, PipeGroup_info, new_allpipelist, flag)
            # 否则，跑水管三通程序:
            else:
                print("程序正在运行第" + str(Group_index) + "组管道，一共有" + str(
                    len(pipeGroups_arr)) + "组管道,当前组管道标号pipeGroup = " + str(PipeGroup.pipeGroupNo))
                progress(Group_index - 1, len(pipeGroups_arr))
                message_info("程序正在运行第" + str(Group_index) + "组管道，一共有" + str(len(pipeGroups_arr)) + "组管道")

                if (PipeGroup.type == 'LineDuct') or (PipeGroup.type == 'Duct'):
                    print('*************当前组(pipeGroupNo =' + str(
                        PipeGroup.pipeGroupNo) + ')管道为含三通风管,跑风管三通算法*************')

                    # plist_flag决定每列管道的排管算法
                    plist_flag = []
                    for i in range(0, len(PipeGroup._pipeLists) + 1):
                        plist_flag.append(flag)
                    Duct_Tee_Sorting(pipeBase, blockBase, block_arr, PipeGroup_info, new_allpipelist, plist_flag)

                else:
                    print(
                        '*************当前组(pipeGroupNo =' + str(PipeGroup.pipeGroupNo) + ')管道含三通水管,跑水管三通算法*************')
                    Tee_sorting(pipeBase, blockBase, block_arr, PipeGroup_info, new_allpipelist, flag)
        except:  # 8.11为了测试新增加的，将跑不通的管道返回原管道
            print('当前管道组(pipeGroupNo =' + str(PipeGroup.pipeGroupNo) + ')排管算法出错,返回原管道!')
            PipeGroup_info = PipeGroupNo_to_PipeGroup(PipeGroup.pipeGroupNo,
                                                      pipeBase)  # PipeGroup_info中的信息为：管道组数组、管道组类型
        
            # 还原pipebase为输入
            for PipeGroup1 in pipeBase_copy._pipeGroups:
                if PipeGroup1.pipeGroupNo == PipeGroup.pipeGroupNo:
                    pipeBase._pipeGroups = [PipeGroup1 if i == PipeGroup else i for i in pipeBase._pipeGroups]
                    break
        
            for pipe in PipeGroup_info[0]:
                new_allpipelist.append(pipe)
                try:
                    new_blocklist = qyhf.pipes_to_blocks(pipe, 10)
                except:
                    break
                # # 管道类型的障碍物，添加到障碍物对象中
                add(new_blocklist, blockBase)
                # # 管道类型的障碍物，添加到障碍物数组中
                block_arr.extend(new_blocklist)
            err_pipegroups += 1
            err_index['Group_index:' + str(Group_index)] = 'pipeGroupNo:' + str(PipeGroup.pipeGroupNo)
        Group_index = Group_index + 1
    # print(pipeBase._pipeGroups[0]._pipeLists[1]._pipes[0].start)
    tee_fitting(pipeBase, pipeBase_copy)  # 为三通管道添加连接关系
    print('所有管道', new_allpipelist)
    print('跑不通的管道组数量:', err_pipegroups)
    print('跑不通的管道组:', err_index)

    # 输出xml
    pipeBase.output_sizeOrder()

    pipeBase.outputXml("C:/revit_data/" + str(id) + "/revit_order_new.xml")

    # 输出检查机制表
    avoiding_obstacles.write_obstacle_results_to_excel(new_allpipelist,
                                                       "C:/revit_data/" + str(id) + "/revit_result.xlsx")




def ID2path(id):
    data_path = "C:/revit_data/" + str(id) + "/revit_data.xml"
    config_path = "C:/revit_data/" + str(id) + "/user_config.xml"
    order_path = "C:/revit_data/" + str(id) + "/revit_order.xml"
    # data_path = "revit_data.xml"
    # config_path = "user_config.xml"
    # order_path = "revit_order.xml"
    # print(data_path, config_path, order_path)
    return [config_path, data_path, order_path]


if __name__ == '__main__':
    # 检测数据库任务，开启事务
    main(ID2path(2818), 2818)
#   updateStatus()
